package com.rockbb.common.sso.cookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionCookieHandler
{
	private SessionCookieHandler() {}

	/**
	 * 根据HttpServletRequest中携带的cookie信息, 填充session需要的cookie值HashMap
	 * 
	 * @param request
	 * @return
	 */
	public static SessionCookies getCookies(HttpServletRequest request) 
	{
		SessionCookies cookies = new SessionCookies();

		Cookie[] requested_cookies = request.getCookies();
		if (requested_cookies != null && requested_cookies.length > 0) 
		{
			for (int i = 0; i < requested_cookies.length; i++ ) 
			{
				for (int j=0; j < SessionCookies.KEYS.length; j++)
				{
					if (requested_cookies[i].getName().equalsIgnoreCase(SessionCookies.KEYS[j])) 
					{
						cookies.setValue(j, requested_cookies[i].getValue());
					}
				}
			}
		}
		return cookies;
	}

	/**
	 * 向HttpServletResponse写入session携带的cookie信息
	 * 
	 * @param response
	 * @param cookies
	 * @param expircy
	 */
	public static void setCookies(HttpServletResponse response, SessionCookies cookies, int expircy) 
	{
		for (int i=0; i<SessionCookies.KEYS.length; i++)
		{
			Cookie cookie = new Cookie(SessionCookies.KEYS[i], cookies.getValue(i));
	        cookie.setMaxAge(expircy);
	        response.addCookie(cookie);
		}
	}

	/**
	 * 向HttpServletResponse写入空白cookie并设置立即失效
	 * 
	 * @param response
	 */
	public static void unSetCookies(HttpServletResponse response) 
	{
		for (int i=0; i<SessionCookies.KEYS.length; i++)
		{
			Cookie cookie = new Cookie(SessionCookies.KEYS[i], "");
	        cookie.setMaxAge(0);
	        response.addCookie(cookie);
		}
	}
}
